iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 10
0

CFML (ColdFusion Markup Language)

Online Course

TryCF

  1. home Home-Page-Code-Example
  2. dfml CFML - A DYNAMIC LANGUAGE - WHAT DOES IT MEAN?
  3. variable INTRODUCING "VARIABLES"
  4. data Data-Types
  5. string Editing-Strings
  6. date WORKING WITH DATES & TIMES
  7. loop LOOPING OVER DATA
  8. array ARRAYS IN COLDFUSION
  9. operator CONDITIONAL STATEMENTS WITH BOOLEANS AND OPERATORS
  10. cfswitch CFSWITCH
  11. structure STRUCTURES IN COLDFUSION
  12. udf COLDFUSION - USER DEFINED FUNCTIONS

Home Page

ColdFusion 主要功能:

  • 能與資料庫連接的網站
  • 簡化的資料庫訪問
  • 客戶端及伺服器端緩存管理
  • 客戶端代碼生成,主要是用於表單控制項和表單的驗證
  • DatePicker、!Datagrid等GUI(圖形用戶界面)控制項
  • 通過引擎將HTML網頁轉換為PDF文件,轉換後的PDF文件保持原網頁的格式、佈超連結
  • 從POP(郵局協定)、HTTP、FTP等常用企業系統,從中收集和檢索數據

CFML

A DYNAMIC LANGUAGE - WHAT DOES IT MEAN?

  1. 不只有 ColdFusion,還有 RAilo, etc...
  2. 是一類在執行時可以改變其結構的語言,範例:
    <cfscript>
        number1 = 5;
        number2 = 6;
        number3 = "7";
        answer1 = number1 + number2;
        answer2 = number1 + number3;
    </cfscript>
    <cfoutput>
        <p>5 + 6 = #answer1#</p>
    <!-- result: 11 -->
        <p>5 + "7" = #answer2#</p>
    <!-- result: 12 -->
    </cfoutput>1
    
  3. 有些 function 可以 判斷資料的類型或 轉換類型,如 isnumeric(variabletocheck)int(theNumberToCast)

INTRODUCING VARIABLES

  1. ColdFusion variable 是不分大小寫的
  2. 螢幕顯示觀察 variable: CFScript: writeOutput(); CF Tag: <cfoutput>
    • NOTE: CFscript 並非設計來給予 Browser 內容的。真正在設計 page 時,用 CF tags 建立 page 來觀察比較好
  3. Ref: Introducing-VARIABLES

Data-Types

  1. 類型:
    1. simple: string, integers, real numbers, Boolean values, date-time values
    2. complex: lists, arrays, structures, queries
    3. binary: raw data, 如 contents of a GIF file, executable program file
    4. object: JAVA, web services, !ColdFusion Component objects, ...
  2. Boolean values: !True/False, 1/0, !Yes/No,不區分大小寫
  3. Lists: 字串(string), 分隔符號(delimiter) 組成,如"apples, bananas, oranges, grapes"。
    1. listLen(): 回傳list的item數
    2. listAppend(): 新增item在list 最後
    3. listPrepend():在list 最前面增加item
    4. listInsertAt(): 再選擇的位置增加item
    • NOTE: MyList is "1,2,,3,,4,,,5" list functions treat it the same as "1,2,3,4,5"
  4. Arrays: 可以儲存 arrays, structs, objects
    1. listToArray(), arrayToList(): array與list 轉換
    2. arrayAvg(), arraySum(), arrayMax(), arrayMin(), arraySort(): 平均數, 總和, 最大值, 最小值, 排序
  5. Structs: 收藏Key-Value pairs,可以儲存 arrays, structs, objects
    1. Keys: 可以筆數字更精確描述資料
    2. structCount():
    3. structKeyExists():
    4. structInsert(): 在struct 最後增加item
    5. structAppend(): 結合兩個structs,不是增加struct
    6. structKeyList(), structKeyArray(): 傳回所有的keys以list, array的形式
    7. structFindKey(), structFindValue(): 傳回要找的值的array
    • NOTE: 當JSON 用到structs時,Javascript是區分大小寫的(case-sentisive),ColdFusion不區分
  6. arrays 與 structs 巢狀結構的範例
    <!--- create initial array --->
    <cfset baseArray = ArrayNew(1)>
    
    <!--- create and populate struct --->
    <cfset childStruct = StructNew()>
    <cfset childStruct.fruit = "Bananas">
    <cfset childStruct['veggie'] = "Zuchinni">
    <cfset structInsert(childStruct,'meat','Steak')>
    
    <!--- add struct to array --->
    <cfset arrayAppend(baseArray,childStruct)>
    
    <!--- 當資料append 在struct時 --->
    <cfset arrayAppend(baseArray,'this is a test')>
    
    <cfdump var=#baseArray#>
    

Ref: Data-Types Tutorials

Editing-Strings

  1. Len(): 回傳字串數量,空格會被計算,範例 Len("Hello ")回傳6,
  2. Trim(): 刪除空格,範例Trim("Hello ")回傳 Hello
  3. Replace(): 取代
    1. 範例: Replace("Hello", "e", "") 回傳 Hllo
    2. 範例: Replace("Good Morning!", "o", "e", "All") 回傳 Geed Merning!
  4. RemoveChars(字串,起始點,距離): 刪除字串,範例: RemoveChars("hello bob", 2, 5) 回傳hbob
  5. Mid(字串,起始點,距離): 截取,範例: Mid("Welcome to CFML Jumpstart",4,12)回傳 come to CFML
  6. 結合字串與變數 ():
    1. 字串聯集 (String concatenation)
    2. 字串插值 (String interpolation)
    <cfset today = DayOfWeekAsString(DayOfWeek((now())))>
    <!--- 字串聯值 --->
    <cfset message = "Happy " & today & "!">
    <!--- 字串插值 --->
    <cfset message="Happy #today#!">
    <cfoutput>
        #message#
    </cfoutput>
    

Ref: Editing-Strings Tutorials

WORKING WITH DATES & TIMES

  1. 建立 Date & Time
    1. Now(), CreateDate (Y,M,D), CreateTime (H,M,S), CreateDateTime (Y,M,D,H,M,S), IsDate (date)
  2. Formatting Dates & Times
    1. DateFormat ("date" [, "mask" ]), TimeFormat ("time"[, "mask" ]), DateTimeFormat ("date/time"[, "mask" ])
    2. Mask Guide: Date Masks, Time Masks (Detail in the tutorial)
  3. 修改 data/time
    1. Parameter Descript: datepart, number, date
  4. 額外的 Date Function
    1. Year("date"), Quarter("date"), Month("date"), Week("date"), Day("date"), Hour("date"), Minute("date"), Second("date")
    2. DaysInYear("date"), DaysInMonth("date"), FirstDayOfMonth("date"), DayOfYear("date"), DayOfWeek("date")
    3. MonthAsString(month_number [, locale]), DayOfWeekAsString(day_of_week [, locale]): Locale 預設是US
      <cfset DateNow = now()>
      <cfoutput>
          Full Date: #datetimeformat(DateNow)#<br/>
          Year: #year(dateNow)# <br/>
          Quarter: #Quarter(dateNow)# <br/>
          Month: #Month(dateNow)# <br/>
          Week: #Week(dateNow)# <br/>
          Day: #Day(dateNow)# <br/>
          Minute: #Minute(dateNow)# <br/>
          Second: #Second(dateNow)# <br/>
          <br/>
          DaysInYear: #DaysInYear(dateNow)# <br/>
          DaysInMonth: #DaysInMonth(dateNow)# <br/>
          <br/>
          FirstDayOfMonth: #FirstDayOfMonth(dateNow)# <br/>
          DayOfYear: #DayOfYear(dateNow)# <br/>
          DayOfWeek: #DayOfWeek(dateNow)# <br/>
          <br/>
          MonthAsString: #MonthAsString(month(dateNow))# <br/>
          DayOfWeekAsString: #DayOfWeekAsString(DayOfWeek(dateNow))# <br/>
      </cfoutput>
      
  5. 時間資料的Loop:
    1. createSpane(Days,Hours,Minutes,Seconds): 建立時間區間的物件
    • 範例:
      <cfset startDate = "01-10-2016">
      <cfset endDate="01-31-2016">
      
      <cfset stepPeriod = createTimeSpan(1,0,0,0)>
      
      <cfloop from = "#startDate#" to = "#endDate#" step="#stepPeriod#" index =         "tempDate">
          <cfoutput>
              #dateformat(tempDate, "mm-dd-yyyy")#<br>
          </cfoutput>
      </cfloop>
      
    • NOTE: 假如endDate 超過31,會顯示錯誤。
  6. 比較2個日期:
    1. DateCompare("date1", "date2" [,"datePart"]): 日期比較
      1. date1 < date2: -1
      2. date1 = date2: 0
      3. date1 > date2: 1
      4. "datepart" : s, n, h, d, m, yyyy
    2. DateDiff("datepart", "date1", "date2"): 日期相差
      1. datepart: yyyy, q, m, y,d, w (weekdays), ww(weeks), h, n, s
      • 範例:
        <cfset dateNow = now()>
        <cfset dateNext = dateAdd("d", 5, dateNow)>
        
        <cfoutput>
            #dateNow#<br>
            #dateNext#<br>
            DateCompare: #DateCompare("#dateNow#", "#dateNext#")#<br>
            DateDiff: #DateDiff("d", #dateNow#, #dateNext#)#
        </cfoutput>
        
  7. fix(): 當日期類的資料備存成其他的資料型態,如number, string時,!coldfusion提供轉換的Function
    • 範例:
      <h3>Date</h3>
      <cfset date = "12-12-2013">
      <cfoutput>
      
      String: #date#<br/>
      
      <cfset dateMod = date + 0>
      Number: #(dateMod)#<br/>
      
      Next Day: #dateformat(dateMod + 1,"mm-dd-yyyy")#<br/>
      
      <h3>Day & Time</h3>
      <cfset dTime = "01-12-2013 1:00 PM">
      
      String: #dTime#<br/>
      
      Decimal: #(dTime + 0)#<br/>
      
      <h3>Date Fix</h3>
      <!--- Demonstrating the fix function --->
      
      Date & Time: #datetimeformat(dTime)#<br/>
      Date w/o Time: #datetimeformat(fix(dTime))#<br/>
      
      </cfoutput>
      
  1. 用事件的方式建立月曆
    1. 使用 Query-of-Queries
    2. CreateODBCDate(date): 日期物件,標準化的ODBC日期格式
    3. CreateODBCTime(date): 時間物件,標準化的ODBC時間格式
    4. CreateODBCDateTime(date): 日期-時間物件, ODBC 標準格式
    • 範例: SQL statement
      <cfquery name="get_events" datasource="test">
      SELECT * FROM events_table
      where date < <cfqueryparam value="#createODBCDate('12/15/2103')#"         cfsqltype="cf_sql_date">
      </cfquery>
      
      <cfset dateNow = now()>
      
      <cfoutput>
          Date: #CreateODBCDate(dateNow)#<br/>
          Time: #CreateODBCTime(dateNow)#<br/>
          Date & Time: #createODBCDateTime(dateNow)#<br/>
      </cfoutput>
      

Ref: WORKING WITH DATES & TIMES Tutorials

LOOPING OVER DATA

Looping Types: Numbers, Lists, Arrays, Structs, Query, Dates, Times, File (loops line by line of file)

  1. Numbers:
    <cfloop from="1" to="100" index="i">
        <cfoutput>#i#</cfoutput>
        <br/>
    </cfloop>
    
  2. Lists:
    <cfset shoppinglist = "apples, banannas, grapes">
    <cfloop list="#shoppinglist#" index="i">
        <cfoutput>#i#</cfoutput>
        <br/>
    </cfloop>
    
  3. Arrays: from方法, array方法
    <cfset shoppinglist = ["apples", "banannas", "grapes"]>
    <!-- from 手法 -->
    <cfloop from=1 to="#arrayLen(shoppinglist)#" index="i">
        <cfoutput>#shoppinglist[i]#</cfoutput>
        <br/>
    </cfloop>
    <!-- array 手法 -->
    <cfloop array="#shoppinglist#" index="i">
        <cfoutput>#i#</cfoutput>
        <br/>
    </cfloop>
    
  4. Structs:
    1. structs 不會記憶順序,所以不能用from
    2. collection,用item 取代index
      <cfset shoppinglist = StructNew()>
      <cfset shoppinglist['apples'] = 'green'>
      <cfset shoppinglist['bannanas'] = 'yellow'>
      <cfset shoppinglist['grapes'] = 'purple'>
      
      <cfloop collection="#shoppinglist#" item="i">
          <!--- in this example "i" is the key --->
          <cfoutput>#i# - #shoppinglist[i]#</cfoutput>
          <br/>
      </cfloop>
      
  5. Query:
    1. query 回傳一個 有行列的table,loop的時候一次是一個row
    2. myQuery取代item, index
    3. 一般皆 <cfoutput>作為輸出
    4. 額外variable
      1. myQuery.RecordCount: 回傳 rows的數量 (常用)
      2. myQuery.CurrentRow: 當前在iterater 的rows
      3. myQuery.ColumnList: query欄 放入用逗號分隔的list 中
    <cfscript>myQuery=queryNew("fruit,color","Integer,Varchar",
    [ ["apples","green"], ["banannas","yellow"], ["grapes","purple"] ]);
    </cfscript>
    <cfdump var=#myQuery# label="Shopping List"><br/>
    <cfoutput>Record Count: #myQuery.RecordCount#</cfoutput><br/>
    <cfoutput>Column List: #myQuery.ColumnList#</cfoutput><br/>
    <!--- Loop over list of items --->
    <cfloop query="#myQuery#">
        <!--- current row of the loop --->
        <cfoutput>#myQuery.CurrentRow#</cfoutput>
    
        <cfoutput>#myQuery.fruit# - #myQuery.color#</cfoutput>
        <br/>
    </cfloop>
    

ARRAYS IN COLDFUSION

  1. arrayNew(): 建立array,arrayLen(): 查array裡面items數量
  2. index 從 1 開始算,且array indice裡面不能放text、負數,放小數會四捨五入能整數
  3. ColdFusion arrays are passed by value to functions [#pass 補充]
  4. array 方法: Array's Method
  5. Looping and data access: coldfusion tag-basedCFScript 提供的looping 語法看起來非常不同,主要 Index Loopsfor-in loops
    1. Index Loops
      1. CFScript: (INITIALIZATION; TEST CONDITION; ITERATOR) { LOOP STATEMENTS }
      2. tag-base: <cfloop index="INITIALIZATION" from="INITIALIZATION" to="TEST CONDITION" [, step=""]></cfloop>
      • 範例: NOTE: 別用arrayLen()在test condition裡面,最佳的做法應該把arrayLen()放在一個變數中,再把變數放在text condition裡面
        <cfset variables.arLoopie = ["Blinky", "Pinky", "Inky", "Clyde", "Sue"] />
        <cfset variables.loopieLen = arrayLen(variables.arLoopie) />
        
        <h5>Index Looping Results</h5>
        <div><em>using tags</em></div>
        <cfoutput>
        <cfloop index="variables.i" from="1" to="#variables.loopieLen#">
            Now we have #variables.arLoopie[variables.i]#<br/>
        </cfloop>
        </cfoutput>
        <hr/>
        <div><em>using cfscript</em></div>
        <cfscript>
            for(variables.x=1; variables.x <= variables.loopieLen; variables.x++ ) {
                writeOutput("So, now we have " & variables.arLoopie[variables.x] & "<br/>");
            }
        </cfscript>
        
    2. For_In Loops: loop over every elements,from, to預設 from="1" to="#arrayLen(arMyArray)#"
      • 範例
        <cfset variables.arLoopie = ["Blinky", "Pinky", "Inky", "Clyde", "Sue"] />
        
        <h5>For-In Looping Results</h5>
        <div><em>using tags</em></div>
        <cfoutput>
        <cfloop index="variables.cur" array="#variables.arLoopie#">
        	Now we have #variables.cur#<br/>
        </cfloop>
        </cfoutput>
        <hr/>
        <div><em>using cfscript</em></div>
        <cfscript>
            for(variables.scriptCur in variables.arLoopie) {
                writeOutput("So, now we have " & variables.scriptCur & "<br/>");
            }
        </cfscript>
        
    3. Loop Backwards: 範例
      1. CFScript: for(variables.x=variables.loopieLen; variables.x >= 1; variables.x-- )
      2. tag-base: <cfloop index="variables.i" from="#variables.loopieLen#" to="3" step="-1"></cfloop>
  6. Sorting Searching and Adding elements
    1. Sorting: arraySort(array, "type", "asc/desc"),array會被重新排列
    2. Searching: arrayFind(array, "search text") 回傳 array 裡的index,"0"代表不存在array裡
    3. Adding: arrayPrepend(array, "element"); arrayPend(array, "element")
  7. Multidimensional arrays: 存在,但不建議使用。更好的東西query object或是 array of structs
    • 範例: array of structs
      <cfscript>
          variables.arLittleMermaidFans = [
              {name="Biff Brubaker", age=37, favsong="Part of Your World"},
              {name="Tammy Temperance", age=59, favsong="Under the Sea"},
              {name="Jim Jabroni", age=12, favsong="Kiss the Girl"}
          ];
      </cfscript>
      <cfoutput>
      <table>
          <tr>
              <th>Name</th>
              <th>Favorite Song</th>
              <th>Age</th>
          </tr>
          <cfloop index="variables.curFan" array="#variables.arLittleMermaidFans#">
              <tr>
                 <td>#variables.curFan.name#</td>
                 <td>#variables.curFan.favsong#</td>
                 <td>#variables.curFan.age#</td>
              </tr>
          </cfloop>
      </table>
      </cfoutput>
      
  8. List v.s Array
    1. 在looping, sorting, searching 使用 Array
    2. 在新增element 在 data collection 之中 使用 list
    3. listToArray(): 讓list 變成 array (這個function 的效率不好,別太常使用)
    • 範例
      <cfscript>
          variables.sillyString = "Sent to spy on a cuban talent show;First stop:Havanago-go!";
      
          variables.arSilly = listToArray(variables.sillyString, " ;:");
      
          writeDump(variables.arSilly);
      </cfscript>
      

Ref: ARRAYS IN COLDFUSION Tutorials

CONDITIONAL STATEMENTS WITH BOOLEANS AND OPERATORS

if

cfscript與cf tag,範例:

```javascript
<cfscript>
if ( true ) {
	WriteOutput( 'The truth is out there.' );
}
</cfscript>
<br />
<cfif true >
    The truth is out there!
</cfif>
```

Conditional-Statements Tutorials

CFSWITCH

範例:

```javascript
<cfset how_you_feel = "Kaput">

<cfswitch expression="#how_you_feel#">
    <cfcase value="Slightly Happy">
		<cfset what_we_should_do = "Eat a bowl of ice cream!">
	</cfcase>
	<cfcase value="Kaput">
		<cfset what_we_should_do = "Stop thinking and go to bed!">
	</cfcase>
	<cfdefaultcase>
		<cfset what_we_should_do = "Stop being such a robot and learn to feel     again! ">
	</cfdefaultcase>
</cfswitch>
<h3>What should I do with this free time!!! ahhhhhhh!</h3>
<cfoutput>
 #what_we_should_do#
</cfoutput>
<!-- result
What should I do with this free time!!! ahhhhhhh!

Stop thinking and go to bed!
-->
```

CFSWITCH Tutorials

STRUCTURES-IN-COLDFUSION

  1. 一次處理多個相同型態的變數
  2. Duplicate(): CFML struct called by refereced,當用structA=structB時,改變structB的內容也會一起改變structA的內容,必須用Duplicate(),才會複製出兩個不相影響的struct variable
    1. structLeyArray(): 傳回struct裡所有的 keys 用array輸出
    2. 範例
      <cfscript>
          variables.structCoke = {
              hasDiet = true,
              slogan = "something about polar bears and santa",
              fakeFact = "actually made out of real polar bear"
          };
      
          variables.structPepsi = Duplicate( variables.structCoke);
          variables.structPepsi.slogan = "Uh-Huh!";
          variables.structPepsi.fakeFact = "Ray Charles was caught with a Diet Coke once,         but Pepsi covered it up";
          variables.structPepsi.reasonToHate = "tastes like bacon"
      
          writeOutput("Coke: " & arrayToList(structKeyArray(variables.structCoke)) &         "<br/>");
            writeOutput("Pepsi: " & arrayToList(structKeyArray(variables.structPepsi)) &         "<br/>");
      </cfscript>
      
  3. structNew() or {}: 建立一個空的struct,keys 是不區分大小寫的,除非使用quotes""包起來去命名,不然 Coldfusion 預設會把 keys 都變大寫
  4. 檢索struct data: Dot Notation MYSTRUCT.MYKEY; Bracket Notation MYSTRUCT["MYKEY"],有一些特殊字元會讓 Dot 失效,如-,但Bracket卻不會。
  5. Add and update struct data:
    1. Dot Notation: myStruct.myNewKey = "my value";,建立的key 不能有特殊字元,不會區分大小寫(對CF而言都是大寫)
    2. Bracket Notation: myStruct["myNewKey"] = "my value";,建立的key可以有特殊字元,會區分大小寫
    3. struct Key 必須要獨特的,CFML不會區分大,小寫,如果有特殊字元必須用 Bracket 去建立struct
  6. structDelete(struct, "target", "true/false"):
    1. target 不存在struct,設"true": 回傳false
    2. 其他情況,其他情況structDelete()都只會回傳true
    3. 範例
      <cfscript>
          variables.structMadeOfWood = {
              furniture = "chair",
              face = "teeth",
              Dutch = "shoes",
              body ="your black heart"
          };
          writeDump(var=variables.structMadeOfWood);
      
          writeOutput(structDelete(variables.structMadeOfWood, "body") & "<br/>");
      
          writeOutput(structDelete(variables.structMadeOfWood, 99, false) & "<br/>");
      
          writeOutput(structDelete(variables.structMadeOfWood, "tubthumpin") & "<br/>");
      
              writeOutput(structDelete(variables.structMadeOfWood, "marmalade", true) &         "<br/>");
      
          writeDump(var=variables.structMadeOfWood);
      </cfscript>
      
  7. Looping: 用 struct loop 會比 array 慢,順序較難預期,所以只能用 collection loop 的方式,並且用Bracket接收 loop 的 data
    <cfset variables.structFootball = {
        "quarterback" = "Russell Wilson",
        "running_back" = "Marshawn Lynch",
        "wide-receiver" = "Percy Harvin",
        "cornerback" = "Richard Sherman"
    }
    />
    <h5>For-In Looping Results</h5>
    <div><em>using tags</em></div>
    <cfoutput>
    <cfloop collection="#variables.structFootball#" item="variables.cur">
    	Our #variables.cur# is #variables.structFootball[variables.cur]#<br/>
    </cfloop>
    </cfoutput>
    
    <hr/>
    
    <div><em>using cfscript</em></div>
    <cfscript>
        for(variables.scriptCur in variables.structFootball) {
            writeOutput("Our " & variables.scriptCur & " is " &     variables.structFootball[variables.scriptCur] & "<br/>");
        }
    </cfscript>
    
  8. Sorting: sturctSort(struct, "type", "ASC/DESC") 不會改變struct,用 structSort 的函數取得的 array 其中包含排好順序的 struct keys
    1. 範例
      <cfset variables.structFootball = {
          "quarterback" = "Russell Wilson",
          "running_back" = "Marshawn Lynch",
          "wide-receiver" = "Percy Harvin",
          "cornerback" = "Richard Sherman"
      }
      />
      <cfset variables.arSortedKeys = structSort(variables.structFootball, "textnocase",         "ASC") />
      
      <h5>For-In Looping Results</h5>
      <div><em>using tags</em></div>
      <cfoutput>
      <cfloop array="#variables.arSortedKeys#" index="variables.cur">
      	Our #variables.cur# #variables.structFootball[variables.cur]#<br/>
      </cfloop>
      </cfoutput>
      
      <hr/>
      
      <div><em>using cfscript</em></div>
      <cfscript>
          for(variables.scriptCur in variables.arSortedKeys) {
              writeOutput("Our " & variables.scriptCur & " is " &         variables.structFootball[variables.scriptCur] & "<br/>");
          }
      </cfscript>
      
  9. scopes 是 structs: scope 變數,如 variables.myString 就是使用 struct Dot Notation
  10. structKeyExists(): 確認 query column 是否存在在CFML query object
    1. 範例:
      <cfscript>
          writeDump(var=variables.qrySluff);
      
          writeOutput("<hr/>Do we know if these people love dogs? " & structKeyExists        (variables.qrySluff, "doglover") & "<br/>");
      
          writeOutput("Do we know if these people love propane? " & structKeyExists        (variables.qrySluff, "propanelover") & "<br/><br/>");
      
          writeOutput("Ages<br/>");
          for(variables.x=1; variables.x<= variables.qrySluff.recordCount; variables.x++)         {
              if(structKeyExists(variables.qrySluff, "age")) {
                  writeoutput(variables.qrySluff["age"][variables.x] & "<br/>");
              }
          }
      </cfscript>
      
  11. structKeyExists(): 確認 component 的方法
    1. 範例
      component name="JellyBelly" accessors="true" {
           property name="color" type="string";
      }
      variables.myJellyBean = new JellyBelly();
      if(structKeyExists(variables.myJellyBean, "getColor")) {
           writeOutput("my jelly's color is " & variables.myJellyBean.getColor() & ".");
      }
      

Ref: Structures-in-ColdFusion Tutorials

COLDFUSION - USER DEFINED FUNCTIONS

  1. 使用function 的目的
    1. 重複使用
    2. 讓 複雜的邏輯過程 變成容易管理的
    3. 需要測試或區隔 其他部分的程式碼
  2. function 必備的兩個item
    1. Definition: name與return 必備
      <cffunction name="MyFirstFunction" returntype="boolean">
          ...
          <cfreturn ... />
      </cffunction>
      
    2. Call
      <cfset results = MyFirstFunction()>
      
  3. NOTE: 作者認為 a function should never output anything to the display! The function should return the result to the main program and then the developer can use the main program to display the output.
  4. 練習: 數字加總
    <cffunction name="SumNumbers" access="private" returntype="numeric">
        <cfargument name="Num1" required="yes" type="numeric">
        <cfargument name="Num2" required="yes" type="numeric">
        <cfset result = Num1 + Num2>
        <cfreturn result>
    </cffunction>
    
    <cfset result = SumNumbers(1,99) />
    
    <cfoutput>#result#</cfoutput>
    

Ref: COLDFUSION - USER DEFINED FUNCTIONS Tutorials

補充

  1. pass by value (傳值call by value): 傳值的意思,就是只把”值”複製給對方
  2. pass by address (傳址call by address): 傳址的意思,就是只把記憶體位址複製給對方
    • 指標是專門用來儲存記憶體的位址,但指標本身也有自己的記憶體位址
  3. pass by reference (傳參考call by reference): 傳址的指標它的內容為指向的位址,但他本身仍然有記憶體位址,但是傳參考是不會有

上一篇
ColdFusion: ColdFusion MX 網站威力實作 part1
下一篇
ColdFusion 練習: ColdFusion MX 網站威力實作 part2
系列文
網頁服務開發之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言